<?php

namespace App\V3\V3_2_7\Services;

use App\Services\CommonService;
use App\V3\V3_2_7\Models\AdminModel;
use App\V3\V3_2_7\Models\AdminPermissionLimitModel;
use App\V3\V3_2_7\Models\LogInStorageModel;
use App\V3\V3_2_7\Models\LogOutStorageModel;
use App\V3\V3_2_7\Models\LogPackageModel;
use App\V3\V3_2_7\Models\MaterielContentModel;
use App\V3\V3_2_7\Models\ModuleModel;
use App\V3\V3_2_7\Models\RoleSettingModel;

use App\V3\V3_2_7\Models\StorageBatchModel;
use App\V3\V3_2_7\Models\StorageManageModel;
use App\V3\V3_2_7\Models\TallyModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use function PHPUnit\Framework\isEmpty;
use App\V3\V3_2_7\Models\StorageModel;

class AdminService
{
    const SALT = 'storage';

    //获取被邀请人信息
    static public function inviteInfo($bindId)
    {
        $arr = [];
        if ($bindId != 0) {
            $bindUserInfo = AdminModel::select('mobile')
                ->where('bind_id', $bindId)
                ->limit(3)
                ->orderBy('id', 'DESC')
                ->get();

            foreach ($bindUserInfo as $value) {
                $arr[] = $value['mobile'];
            }
        }

        return $arr;
    }

    //子账号列表
    static public function userList($mainId, $data)
    {
        return AdminModel::userList($mainId, $data);
    }

    //检查子账户是否存在
    static public function checkUser($id)
    {
        if (!empty(AdminModel::where('id', $id)->first())) {
            return true;
        } else {
            return false;
        }
    }

    //审批人列表
    public static function approverList($mainId)
    {
        $list = AdminModel::getApproverList($mainId);
        if (!empty($list->toArray())) {
            $list = $list->toArray();
            foreach ($list as &$value) {
                if (!empty($value['parent_id'])) {
                    $value['per_type'] = 0;
                    $perInfo = AdminPermissionLimitModel::query()->where([
                        'user_id' => $value['id'],
                        'module_id' => 92
                    ])->first();
                    if (!empty($perInfo)) {
                        $value['per_type'] = $perInfo['type'];
                    }
                } else {
                    $value['per_type'] = 1;
                }
            }
        }
        return $list;
    }

    //重置指定子账号登录密码
    public static function resetPwd($data, $checkUser): ?array
    {
        $randNo = rand(000000, 999999);

        do {
            $randNo = rand(000000, 999999);
        } while (!empty(
        AdminModel::where('parent_id', '!=', 0)
            ->where([
                'delete_flag' => 0,
                'newpwd' => $randNo
            ])->first()
        ));

        $isUpdate = AdminModel::where('id', $data['id'])->update([
            'newpwd' => $randNo,
//            'is_default_pwd' => 0
        ]);

        if ($isUpdate !== false) {
            return ['code' => 0, 'msg' => 'success', 'data' => ''];
        }

        return ['code' => 0, 'msg' => '密码重置失败，请重试', 'data' => ''];
    }

    //检查子账号是否已存在
    static public function checUserInfo($mainId, $data)
    {
        $userInfo = AdminModel::where([
            'username' => $data['username'],
            'delete_flag' => 0
        ])
            ->where('parent_id', '!=', 0)
            ->first();

        if (empty($userInfo)) {
            return true;
        } else {
            return false;
        }
    }

    //新建子账号
    static public function addUser($mainId, $data, $time)
    {
        $mainInfo = AdminModel::where('id', $mainId)->first();

        $data['parent_id'] = $mainId;
        $randNo = rand(100000, 999999);

        do {
            $randNo = rand(100000, 999999);
        } while (!empty(AdminModel::where('parent_id', '!=', 0)
            ->where([
                'delete_flag' => 0,
                'newpwd' => $randNo
            ])->first()));

        $data['password'] = md5(md5('123456' . self::SALT));
        $data['newpwd'] = empty($data['newpwd']) ? $randNo : $data['newpwd'];
        if (strlen($data['newpwd']) < 6) {
            return ['code' => 1, 'msg' => '密码最小为6位字符', 'data' => ''];
        }
        $data['company_name'] = empty($mainInfo['company_name']) ? '' : $mainInfo['company_name'];
        $data['company_class'] = $mainInfo['company_class'];
        $data['created_at'] = time();
        $data['is_active'] = $data['is_active'];

        unset($data['status']);

        $userId = AdminModel::insertGetId($data);

        $result = ['code' => 0, 'msg' => 'success', 'data' => ['id' => $userId]];

        return $result;
    }

    public static function getUserPermission($mainId, $userInfo)
    {
        $parentModuleInfo = self::parentModuleInfo($mainId);

        //获取子账号一级模块
        $userFirstModuleInfo = AdminPermissionLimitModel::getUserFirstModuleInfo($userInfo['id']);
        //获取子账号二级模块
        $userSecondModuleInfo = AdminPermissionLimitModel::getUserSecondModuleInfo($userInfo['id']);

        $firstModuleIdArr = [];
        foreach ($userFirstModuleInfo as $firstModuleValue) {
            $firstModuleIdArr[] = $firstModuleValue['module_id'];
        }

        $secondModuleIdArr = [];
        foreach ($userSecondModuleInfo as $secondModuleValue) {
            $secondModuleIdArr[] = $secondModuleValue['module_id'];
        }

        $arr = [];
        foreach ($parentModuleInfo as $key => $value) {
            $arr[$key]['id'] = $value['id'];
            $arr[$key]['module_name'] = $value['module_name'];
            $arr[$key]['type'] = $value['type'];
            $arr[$key]['sort'] = $value['sort'];
            $arr[$key]['upper_module_id'] = $value['upper_module_id'];
            $arr[$key]['module_img'] = empty($value['module_img']) ? '' : $value['module_img'];


            if (in_array($value['id'], $firstModuleIdArr, true)) {
                $arr[$key]['is_enable'] = 1;
            } else {
                $arr[$key]['is_enable'] = 0;
            }

            if (!empty($value['second_module'])) {
                foreach ($value['second_module'] as $k => $v) {
                    $arr[$key]['second_module'][$k]['module_img'] = empty($v['module_img']) ? '' : $v['module_img'];
                    if (in_array($v['id'], $secondModuleIdArr, true)) {
                        $arr[$key]['second_module'][$k]['is_enable'] = 1;
                    } else {
                        $arr[$key]['second_module'][$k]['is_enable'] = 0;
                    }

                    $moduleInfo = AdminPermissionLimitModel::where('user_id', $userInfo['id'])
                        ->where('module_id', $v['id'])->first();

                    $arr[$key]['second_module'][$k]['id'] = $v['id'];
                    $arr[$key]['second_module'][$k]['module_name'] = $v['module_name'];
                    $arr[$key]['second_module'][$k]['type'] = $v['type'];
                    $arr[$key]['second_module'][$k]['sort'] = $v['sort'];
                    $arr[$key]['second_module'][$k]['upper_module_id'] = $v['upper_module_id'];
                    $arr[$key]['second_module'][$k]['operate_type'] = empty($moduleInfo['type']) ? 0 : $moduleInfo['type'];
                }
            } else {
                $arr[$key]['second_module'] = [];
            }
        }

        return $arr;
    }

    //获取子账号权限信息v3.2.1以前版本支持
    public static function getUserPermissionOld($mainId, $userInfo): array
    {
        $parentModuleInfo = self::parentModuleInfo($mainId);

        $userFirstModuleArr = array_filter(explode(',', $userInfo['first_module']), function ($v) {
            return $v !== '';
        });
        $userSecondModuleArr = array_filter(explode(',', $userInfo['second_module']), function ($v) {
            return $v !== '';
        });

        // $moduleInfo = ModuleService::roleModuleList();

        $arr = [];
        foreach ($parentModuleInfo as $key => $value) {
            $arr[$key]['id'] = $value['id'];
            $arr[$key]['module_name'] = $value['module_name'];
            $arr[$key]['type'] = $value['type'];
            $arr[$key]['sort'] = $value['sort'];
            $arr[$key]['upper_module_id'] = $value['upper_module_id'];
            $arr[$key]['module_img'] = empty($value['module_img']) ? '' : $value['module_img'];


            if (in_array($value['id'], $userFirstModuleArr, true)) {
                $arr[$key]['is_enable'] = 1;
            } else {
                $arr[$key]['is_enable'] = 0;
            }

            if (!empty($value['second_module'])) {
                foreach ($value['second_module'] as $k => $v) {
                    $arr[$key]['second_module'][$k]['module_img'] = empty($v['module_img']) ? '' : $v['module_img'];
                    if (in_array($v['id'], $userSecondModuleArr, true)) {
                        $arr[$key]['second_module'][$k]['is_enable'] = 1;
                    } else {
                        $arr[$key]['second_module'][$k]['is_enable'] = 0;
                    }

                    $arr[$key]['second_module'][$k]['id'] = $v['id'];
                    $arr[$key]['second_module'][$k]['module_name'] = $v['module_name'];
                    $arr[$key]['second_module'][$k]['type'] = $v['type'];
                    $arr[$key]['second_module'][$k]['sort'] = $v['sort'];
                    $arr[$key]['second_module'][$k]['upper_module_id'] = $v['upper_module_id'];
                }
            } else {
                $arr[$key]['second_module'] = [];
            }
        }

        return $arr;
    }

    private static function parentModuleInfo($mainId)
    {
        $moduleInfo = AdminModel::select(
            'b.first_module',
            'b.second_module'
        )
            ->from('admin as a')
            ->leftJoin('role_setting as b', 'b.role_id', '=', 'a.admin_role')
            ->where('a.id', $mainId)->first();

        $firstModule = array_filter(explode(',', $moduleInfo['first_module']), function ($v) {
            return $v !== '';
        });
        $secondModule = array_filter(explode(',', $moduleInfo['second_module']), function ($v) {
            return $v !== '';
        });

        return ModuleModel::usefulPermission($firstModule, $secondModule);
    }

    //检查旧密码是否正确
    static public function checkPwd($userId, $data)
    {
        $userInfo = AdminModel::where('id', $userId)->first();

        if ($data['old_pwd'] != $userInfo['newpwd']) {
            return false;
        } else {
            return true;
        }
    }

    //子账号修改登录密码
    static public function changePwd($userId, $data)
    {
        AdminModel::where('id', $userId)->update([
            'newpwd' => $data['new_pwd'],
//            'is_default_pwd' => 1
        ]);

        return true;
    }

    //个人中心
    static public function userCenter($userId, $mainId, $userType)
    {
        $data = AdminModel::select(
            'a.id',
            'username',
            'nickname',
            'mobile',
            'parent_id',
            'company_name',
            'company_class',
            'is_active',
            'bind_id',
            'invite_num',
            'b.name',
            'is_default_pwd',
            'openid as is_bind_openid',
            'wx_nickname',
            'service_phone',
            'company_address',
            'batch_title',
            'first_module',
            'second_module',
            'auto_storage_switch',
            'gz_openid',

        )
            ->from('admin as a')
            ->leftJoin('company_class as b', 'a.company_class', '=', 'b.id')
            ->where('a.id', $userId)->first();

        $startTime = strtotime(date('Y-m-d'));
        $endTime = strtotime(date('Y-m-d 23:59:59'));

        if ($userId == $mainId) {
            $condition['main_id'] = ['EQ' => $mainId];
            unset($data['is_default_pwd']);
        } else {
            $condition['user_id'] = ['EQ' => $userId];
        }

        $mainInfo = AdminModel::select(
            'admin.*',
            'is_vip',
            'is_set_as_supplier',
            'is_share_customer',
            'is_in_experience',
            'is_end_experience',
            'vip_end_date',
            'is_share_express',
            'is_first_charge',
            'is_use_shelf',
            'is_use_serial',
            'account_storage',
            'file_total_size',
            'is_share_shelf_location',
            'is_use_packages_components',
            'clear_watermark_or_not',
            'customer_supplier_sync_price'
        )
            ->where([
                'admin.id' => $mainId,
            ])->leftJoin('admin_addendum as b', 'b.main_id', '=', 'admin.id')->first();
        if ($mainInfo['is_vip'] > 0 && $mainInfo['invite_num'] < 3) {
            $mainInfo['invite_num'] = 3;
        }
        $data['company_name'] = empty($mainInfo['company_name']) ? "" : $mainInfo['company_name'];
        $data['parent_id'] = $mainId;
        $data['bind_id'] = $mainInfo['bind_id'];
        $data['invite_num'] = 3/*$mainInfo['invite_num']*/
        ;
        $data['invite_info'] = self::inviteInfo($mainId);
        $data['is_bind_openid'] = empty($data['is_bind_openid']) ? 0 : 1;
        $data['is_vip'] = $mainInfo['is_vip'];
        $data['customer_supplier_sync_price'] = $mainInfo['customer_supplier_sync_price'];
//        $data['is_share_customer'] = $mainInfo['is_share_customer'];
        $data['is_in_experience'] = $mainInfo['is_in_experience'];
        $data['is_end_experience'] = $mainInfo['is_end_experience'];
        $data['vip_end_date'] = $mainInfo['vip_end_date'];
//        $data['is_share_express'] = $mainInfo['is_share_express'];
        $data['is_first_charge'] = $mainInfo['is_first_charge'];
//        $data['is_use_serial'] = $mainInfo['is_use_serial'];
        $data['account_storage'] = sprintf('%.2f', $mainInfo['account_storage'] / 1024 / 1024);
        $data['file_total_size'] = sprintf('%.2f', $mainInfo['file_total_size'] / 1024 / 1024);
//        $data['clear_watermark_or_not'] = $mainInfo['clear_watermark_or_not'];
        $data['today_in_storage'] = LogInstorageModel::getTodayInCount($condition, $startTime, $endTime);//今日入库总数
        $data['today_out_storage'] = LogOutStorageModel::getTodayOutCount($condition, $startTime, $endTime);//今日出库
//        $data['today_package'] = LogPackageModel::getTodayPackageCount($condition, $startTime, $endTime);//今日套餐出库总数
        $data['today_trans_storage'] = LogOutstorageModel::getTodayAllocateCount($condition, $startTime, $endTime);//今日调拨数量
        /*$data['today_storage_warning'] = StorageManageModel::getTodayStorageWanringCount($condition, $startTime, $endTime);//今日预警数量
        $data['today_sell_money'] = SellModel::getTodaySellMoney($condition, $startTime, $endTime);//今日销售金额
        $data['today_tally_income'] = TallyModel::getTodayTallyImcome($condition, 0,$startTime, $endTime);//今日账单收入
        $data['today_total_money'] = $data['today_sell_money']+$data['today_tally_income'];//今日总收入
        $data['today_purchase_money'] = MaterielContentModel::getTodayMaterielMoney($condition, $startTime, $endTime);//今日采购金额
        $data['today_tally_expend'] = TallyModel::getTodayTallyImcome($condition,1, $startTime, $endTime);//今日账单支出
        $data['today_total_money'] = $data['today_purchase_money']+$data['today_tally_expend'];//今日总支出*/
//        switch($userType) {
//            case 0:
//                $result = self::mainGetModelInfo($userId);
//                break;
//            default:
//                $result = self::userGetModelInfo($userId);
//        }
        $data['is_share_shelf_location'] = $mainInfo['is_share_shelf_location'];
        $data['is_use_shelf'] = $mainInfo['is_use_shelf'];
        $data['company_logo_img'] = $mainInfo['company_logo_img'];
        $data['profile_photo_img'] = $mainInfo['profile_photo_img'];
        $data['remark'] = $mainInfo['remark'];
        $data['is_main'] = $mainId == $userId ? 1 : 0;
//        $data['module_info'] = $result;
        $data['is_use_packages_components'] = $mainInfo['is_use_packages_components'];
        unset($data['first_module']);
        unset($data['second_module']);

        $data['field_list'] = DataFieldService::distinguishPermissionList($userId);
        $data['child_account_num'] = AdminModel::query()->where([
            'parent_id'=>$mainId,
            'delete_flag'=>0,
        ])->count();
        return $data;
    }

    //查看被邀请人列表
    static public function inviteList($mainId, $data)
    {
        $result = AdminModel::select('nickname', 'mobile')->where('bind_id', $mainId)
            ->orderBy('id', 'DESC')
            ->paginate($data['pageSize'], ['*'], '', $data['currentPage']);

        return $result;
    }

    static public function setPwd($data)
    {
        AdminModel::where('id', $data['id'])
            ->update([
                'password' => md5(md5($data['password'] . self::SALT))
            ]);

        return true;
    }

    static public function transOutWay($mainId)
    {
        $mainInfo = AdminModel::where('id', $mainId)->first();

        DB::beginTransaction();

        try {
            //变更出库方式
            $updateData = [];
            if ($mainInfo['out_storage_way'] == 0) {
                $updateData['out_storage_way'] = 1;
            } else {
                $updateData['out_storage_way'] = 0;
            }
            AdminModel::where('id', $mainId)->update($updateData);
            AdminModel::where('parent_id', $mainId)->update($updateData);

            $storageBatchInfo = StorageBatchModel::select('id')
                ->where('batch_left_num', '!=', 0)
                ->where('main_id', $mainId)->get()->toArray();

            $time = time();
            foreach ($storageBatchInfo as $value) {
                $batchNo = $mainInfo['batch_title'] . date('YmdHis', $time) . mt_rand(1000, 9999) . '0';

                do {
                    $batchNo = $mainInfo['batch_title'] . date('YmdHis', $time) . mt_rand(1000, 9999) . '0';
                } while (!empty(StorageBatchModel::where('main_id', $mainId)
                    ->where('batch_no', $batchNo)->first()));

                StorageBatchModel::where('id', $value['id'])
                    ->update([
                        'batch_no' => $batchNo
                    ]);
            }

            DB::commit();
            return ['code' => 0, 'msg' => 'success', 'data' => ''];
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('转换出库方式异常:' . var_export($e->getMessage(), true));
            return ['code' => 1, 'msg' => '转换失败,请重试', 'data' => ''];
        }
    }

    public static function mainGetModelInfo(int $userId)
    {
        $adminInfo = AdminModel::getAccountInfo($userId);
        $roleInfo = RoleSettingModel::where('role_id', $adminInfo['admin_role'])->first();

        $userFirstModuleArr = array_filter(explode(',', $roleInfo['first_module']), function ($v) {
            return $v !== '';
        });
        $userSecondModuleArr = array_filter(explode(',', $roleInfo['second_module']), function ($v) {
            return $v !== '';
        });

        return self::adminModule($userFirstModuleArr, $userSecondModuleArr);
    }

    public static function userGetModelInfo(int $userId)
    {
        $userInfo = AdminModel::getAccountInfo($userId);

//        $userFirstModuleArr = array_filter(explode(',', $userInfo['first_module']), function($v) { return $v !== ''; });
//        $userSecondModuleArr = array_filter(explode(',', $userInfo['second_module']), function($v) { return $v !== ''; });

        //获取子账号一级模块
        $userFirstModuleInfo = AdminPermissionLimitModel::getUserFirstModuleInfo($userId);
        //获取子账号二级模块
        $userSecondModuleInfo = AdminPermissionLimitModel::getUserSecondModuleInfo($userId);

        $firstModuleIdArr = [];
        foreach ($userFirstModuleInfo as $firstModuleValue) {
            $firstModuleIdArr[] = $firstModuleValue['module_id'];
        }

        $secondModuleIdArr = [];
        foreach ($userSecondModuleInfo as $secondModuleValue) {
            $secondModuleIdArr[] = $secondModuleValue['module_id'];
        }

        return self::userModule($userId, $firstModuleIdArr, $secondModuleIdArr);
    }

    private static function userModule($userId, array $firstModuleIdArr, array $secondModuleIdArr): array
    {
        $firstModuleInfo = ModuleModel::select(
            'id',
            'module_name',
            'upper_module_id',
            'module_img',
            'type',
            'sort',
            'icon',
            'url1',
            'url2',
            'platform'
        )
            ->whereIn('id', $firstModuleIdArr)
            ->where('delete_flag', 0)
            ->orderBy('sort', 'asc')
            ->orderBy('id', 'DESC')
            ->get()->toArray();

        $secondModuleInfo = ModuleModel::select(
            'id',
            'module_name',
            'upper_module_id',
            'module_img',
            'type',
            'sort',
            'icon',
            'url1',
            'url2',
            'platform'
        )
            ->whereIn('id', $secondModuleIdArr)
            ->where('delete_flag', 0)
            ->orderBy('sort', 'asc')
            ->orderBy('id', 'DESC')
            ->get()->toArray();

        foreach ($firstModuleInfo as $key => &$value) {
            if (!empty($value['platform'])) {
                $value['platform'] = array_filter(explode(',', $value['platform']), function ($v) {
                    return $v !== '';
                });
            } else {
                $value['platform'] = [];
            }

            foreach ($secondModuleInfo as $k => $v) {
                if ($value['id'] == $v['upper_module_id']) {
                    $moduleInfo = AdminPermissionLimitModel::where('user_id', $userId)
                        ->where('module_id', $v['id'])->first();

                    $firstModuleInfo[$key]['second_module'][] = [
                        'id' => $v['id'],
                        'module_name' => $v['module_name'],
                        'upper_module_id' => $v['upper_module_id'],
                        'module_img' => $v['module_img'],
                        'operate_type' => $moduleInfo['type'],
                        'sort' => $v['sort'],
                        'icon' => $v['icon'],
                        'url1' => $v['url1'],
                        'url2' => $v['url2'],
                        'platform' => empty($v['platform']) ? [] : array_filter(explode(',', $v['platform']), function ($v1) {
                            return $v1 !== '';
                        }),
                    ];
                }
            }
        }

        return $firstModuleInfo;
    }

    private static function adminModule(array $userFirstModuleArr, array $userSecondModuleArr)
    {
        $firstModuleInfo = ModuleModel::select(
            'id',
            'module_name',
            'upper_module_id',
            'module_img',
            'type',
            'sort',
            'icon',
            'url1',
            'url2',
            'platform'
        )
            ->whereIn('id', $userFirstModuleArr)
            ->where('delete_flag', 0)
            ->orderBy('sort', 'asc')
            ->orderBy('id', 'DESC')
            ->get()->toArray();

        $secondModuleInfo = ModuleModel::select(
            'id',
            'module_name',
            'upper_module_id',
            'module_img',
            'type',
            'sort',
            'icon',
            'url1',
            'url2',
            'platform'
        )
            ->whereIn('id', $userSecondModuleArr)
            ->where('delete_flag', 0)
            ->orderBy('sort', 'asc')
            ->orderBy('id', 'DESC')
            ->get()->toArray();

        foreach ($firstModuleInfo as $key => &$value) {
            if (!empty($value['platform'])) {
                $value['platform'] = array_filter(explode(',', $value['platform']), function ($v) {
                    return $v !== '';
                });
            } else {
                $value['platform'] = [];
            }

            foreach ($secondModuleInfo as $k => $v) {
                if ($value['id'] == $v['upper_module_id']) {
                    $firstModuleInfo[$key]['second_module'][] = [
                        'id' => $v['id'],
                        'module_name' => $v['module_name'],
                        'upper_module_id' => $v['upper_module_id'],
                        'module_img' => $v['module_img'],
                        'operate_type' => 0,
                        'sort' => $v['sort'],
                        'icon' => $v['icon'],
                        'url1' => $v['url1'],
                        'url2' => $v['url2'],
                        'platform' => empty($v['platform']) ? [] : array_filter(explode(',', $v['platform']), function ($v1) {
                            return $v1 !== '';
                        }),
                    ];
                }
            }
        }

        return $firstModuleInfo;
    }

    //设置子账号功能仅查看权限
    public static function setPermissionLimit(array $data): ?array
    {
        $moduleInfo = json_decode($data['module_info'], true, 512, JSON_THROW_ON_ERROR);

        try {
            //获取用户已有的权限限制信息
            $getUserPermissionLimitInfo = AdminPermissionLimitModel::getUserPermissionLimit($data['user_id']);

            if (!empty($getUserPermissionLimitInfo)) {
                AdminPermissionLimitModel::query()->where('user_id', $data['user_id'])->delete();
            }

            $arr = [];
            foreach ($moduleInfo as $value) {
                $arr[] = [
                    'module_id' => $value['module_id'],
                    'upper_module_id' => $value['upper_module_id'],
                    'user_id' => $data['user_id'],
                    'main_id' => $data['main_id'],
                    'created_at' => time()
                ];
            }

            if (!empty($arr)) {
                AdminPermissionLimitModel::query()->insert($arr);
            }

            DB::commit();
            return ['code' => 0, 'msg' => 'success', 'data' => ''];
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('设置功能仅查看权限失败:' . var_export($e->getMessage(), true));
            return ['code' => 1, 'msg' => '设置权限失败', 'data' => ''];
        }
    }

    //设置子账号权限
    public static function setUserPermissions(array $adminData)
    {
        $getUserOldPermissions = AdminPermissionLimitModel::getUserOldPermissions($adminData);

        if (!empty($getUserOldPermissions)) {
            AdminPermissionLimitModel::query()->where('user_id', $adminData['id'])->delete();
        }

//        $firstModuleInfo = array_filter(explode(',', $adminData['first_module']), function($v) { return $v !== ''; });

        $firstModuleArr = [];
//        foreach($firstModuleInfo as $firstModuleValue) {
//            $firstModuleArr[] = [
//                'module_id' => $firstModuleValue,
//                'user_id' => $adminData['id'],
//                'main_id' => $adminData['main_id'],
//                'created_at' => time()
//            ];
//        }

        $secondModuleInfo = json_decode($adminData['second_module'], true);

        $secondModuleArr = [];
        foreach ($secondModuleInfo as $secondModuleValue) {
            if (!isset($firstModuleArr[$secondModuleValue['upper_module_id']])) {
                $firstModuleArr[$secondModuleValue['upper_module_id']] = [
                    'module_id' => $secondModuleValue['upper_module_id'],
                    'user_id' => $adminData['id'],
                    'main_id' => $adminData['main_id'],
                    'created_at' => time()
                ];
            }

            $secondModuleArr[] = [
                'module_id' => $secondModuleValue['module_id'],
                'upper_module_id' => $secondModuleValue['upper_module_id'],
                'user_id' => $adminData['id'],
                'main_id' => $adminData['main_id'],
                'type' => $secondModuleValue['type'],
                'created_at' => time()
            ];
        }

        AdminPermissionLimitModel::insert($firstModuleArr);
        AdminPermissionLimitModel::insert($secondModuleArr);

        return true;
    }

    /**
     * 用户列表
     * @param array $data
     */
    static public function getUserList(array $data)
    {
        $query = AdminModel::select(
            'a.id',
            'a.username',
            'a.nickname',
            'a.company_name',
            'a.created_at',
            'is_vip',
            'vip_end_date',
            'account_storage',
            'storage_end_date'
        )->from('admin as a')
            ->leftJoin('admin_addendum as b', 'b.main_id', '=', 'a.id')
            ->where([
                'delete_flag' => 0,
                'is_active' => 1,
                'is_vip' => 1,
                ['parent_id', '=', 0],
                'a.admin_role' => 2
            ]);
        if (!empty($data['keyword'])) {
            $query->where(function ($query) use ($data) {
                $query->orWhere('a.username', 'like', '%' . $data['keyword'] . '%');
                $query->orWhere('a.nickname', 'like', '%' . $data['keyword'] . '%');
                $query->orWhere('a.company_name', 'like', '%' . $data['keyword'] . '%');
            });
        }
        return $query->orderBy('is_vip', 'desc')
            ->orderBy('created_at', 'desc')
            ->paginate($data['pageSize'], ['*'], '', $data['currentPage'])->toArray();
    }

    /**
     * 用户管理列表
     * @param array $data
     */
    static public function getUserManageList(array $data)
    {
        $query = AdminModel::select(
            'id',
            'username',
            'nickname',
            'company_name',
            'is_active',
            'remark'
        )->where([
            'delete_flag' => 0,
            ['parent_id', '=', 0],
            'admin_role' => 2
        ]);
        if (!empty($data['keyword'])) {
            $query->where(function ($query) use ($data) {
                $query->orWhere('username', 'like', '%' . $data['keyword'] . '%');
                $query->orWhere('nickname', 'like', '%' . $data['keyword'] . '%');
                $query->orWhere('company_name', 'like', '%' . $data['keyword'] . '%');
            });
        }
        return $query->orderBy('created_at', 'desc')
            ->paginate($data['pageSize'], ['*'], '', $data['currentPage'])->toArray();
    }

    //选择用户列表
    public static function selUserList($data)
    {
        $list = AdminModel::selUserList($data);
        $totalStorageList = StorageModel::select(
            'user_id',
            'multi_user_id',
            'storage_name'
        )->where([
            'main_id' => $data['main_id'],
            'delete_flag' => 0
        ])->get();
        if (!empty($totalStorageList)) {
            $totalStorageList = $totalStorageList->toArray();
        }
        if (!empty($list['data'])) {
            foreach ($list['data'] as &$val) {
                /* $pStorageList = [];
                 $uStorageList = [];
                 if(!empty($totalStorageList)){
                     foreach ($totalStorageList as $sVal){
                         if(!empty($sVal['user_id'])){
                             if($sVal['user_id'] ==$val['id']){
                                 $pStorageList[] = $sVal['storage_name'];
                             }
                         }
                         if(!empty($sVal['multi_user_id'])){
                             $multiUserIdArr = explode(',', $sVal['multi_user_id']);
                             if(in_array($val['id'], $multiUserIdArr)){
                                 $uStorageList[] = $sVal['storage_name'];
                             }
                         }
                     }
                 }*/
                $val['principal_storage_list'] = /*$pStorageList*/
                    [];
                $val['user_storage_list'] = /*$uStorageList*/
                    [];
            }
        }
        return $list;
    }
}
